import { Injectable } from '@nestjs/common'
import { CreateTrackwebDto } from './dto/create-trackweb.dto'
import { UpdateTrackwebDto } from './dto/update-trackweb.dto'
import { PrismaService } from '@/prisma/prisma.service'
import * as fs from 'fs'
import { md5 } from 'js-md5'
import * as path from 'path'

@Injectable()
export class TrackwebService {
  constructor(private readonly prisma: PrismaService) {}
  async create(createTrackwebDto: CreateTrackwebDto) {
    const baseInfo = await this.prisma.baseInfo.create({
      data: {
        ...createTrackwebDto.baseInfo,
        sendTime: String(createTrackwebDto.baseInfo.sendTime),
      },
    })
    const recordscreen = this.writhFile(createTrackwebDto.eventInfo[0].recordscreen)
    const trackInfo = await this.prisma.eventInfo.create({
      data: {
        ...createTrackwebDto.eventInfo[0],
        recordscreen,
        triggerTime: String(createTrackwebDto.eventInfo[0].triggerTime),
        sendTime: String(createTrackwebDto.eventInfo[0].sendTime),
      },
    })
    return { baseInfo, trackInfo }
  }

  async findAll() {
    const data = await this.prisma.eventInfo.findMany()

    return data.map((item) => ({
      ...item,
      triggerTime: Number(item.triggerTime),
      sendTime: Number(item.sendTime),
      recordscreen: this.readFile(item.recordscreen) || null,
    }))
  }

  findOne(id: number) {
    return `This action returns a #${id} trackweb`
  }

  update(id: number, _updateTrackwebDto: UpdateTrackwebDto) {
    return `This action updates a #${id} trackweb`
  }

  remove(id: number) {
    return `This action removes a #${id} trackweb`
  }
  writhFile(value: string) {
    const fileName = md5(value)
    const rootDir = path.resolve(__dirname, '../../uploads/')
    const filePath = path.join(rootDir, `${fileName}.txt`)
    fs.writeFileSync(filePath, value)
    return `${fileName}.txt`
  }
  readFile(fileName: string) {
    console.log('fileName', fileName)
    const rootDir = path.resolve(__dirname, '../../uploads/')
    const filePath = path.join(rootDir, `${fileName}`)
    return fs.readFileSync(filePath, 'utf-8')
  }
}
